<template>
  <div class="app-container">
    <div class="filter-container right">
      <el-button
        v-waves
        class="filter-item"
        type="success"
        icon="el-icon-plus"
        @click="dialogFormVisible = true"
      >
        添加
      </el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="tableData"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      ref="dataForm"
    >
      <el-table-column label="编号" align="center" width="80">
        <template slot-scope="{ row }">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="产品名称" class-name="status-col" width="90">
        <template slot-scope="{ row }">
          {{ row.name }}
        </template>
      </el-table-column>
      <el-table-column label="匹配地区" min-width="120" align="center">
        <template slot-scope="{ row }">
          {{ row.matchRegion }}
        </template>
      </el-table-column>
      <el-table-column label="推广页链接" class-name="status-col" width="230">
        <template slot-scope="{ row }">
          {{ row.h5 }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        min-width="140"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button type="primary" size="mini" @click="editLabel(row)">
            编辑
          </el-button>
          <el-button type="danger" size="mini" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="findAll"
    />

    <!-- 编辑 -->
    <el-dialog title="编辑" :visible.sync="dialogFormVisible1" width="90%" :before-close="cancel1">
      <el-form :model="form1" :rules="rules1" ref="form1">
        <el-form-item label="产品名称" :label-width="formLabelWidth">
          <el-select ref='selectLable1' v-model="form1.loanAppId" placeholder="请选择产品名称">
              <el-option
              v-for="(item, id) in selectArr"
              :key="id"
              :value="item.id"
              :label="item.appName"
            >
              {{ item.appName }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="匹配地区" label-width="70px" prop="matchRegion1">
          <!-- <el-input v-model="form1.matchRegion"></el-input> -->
          <el-cascader
            v-model="form1.matchRegion"
            size="large"
            :props="props"
            collapse-tags
            :options="cityoptions"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel1">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 新增 -->
    <el-dialog title="添加" :visible.sync="dialogFormVisible" width="90%" :before-close="cancel">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="产品名称" label-width="100px" prop="loanAppId">
          <el-select ref='selectLable' v-model="form.loanAppId" placeholder="请选择产品名称">
              <el-option
              v-for="(item, id) in selectArr"
              :key="id"
              :value="item.id"
              :label="item.appName"
            >
              {{ item.appName }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="匹配地区" label-width="100px" prop="matchRegion">
          <!-- <el-input v-model="form.matchRegion"></el-input> -->
          <el-cascader
            v-model="form.matchRegion"
            size="large"
            :props="props"
            collapse-tags
            clearable
            :options="cityoptions"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary" @click="add()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { TextToCode, CodeToText, provinceAndCityData } from 'element-china-area-data'
import {
 getRegionalProducts,list,addRegionalProducts,removeByAppId
} from "@/api/deploy";
import waves from "@/directive/waves";
import Pagination from "@/components/Pagination";

export default {
  name: "Channellist",
  components: { Pagination },
  directives: { waves },
  data() {
    // var validatePass2=(rule, value, callback)=>{
    //   let a=this.form.matchRegion.split(/[，。？：；‘’！“”—……、,]/gi)
    //     var z = []
    //     a.filter(function(item){
    //       if(item.slice(-1) != "市"){
    //         z.push(item) 
    //       }
    //     })
    //     if (z.length!==0){
    //       callback(new Error('请输入正确的地区格式'))
    //     }else{
    //       callback()
    //     }
    // };
    // var validatePass1=(rule, value, callback)=>{
    //   let a=this.form1.matchRegion.split(/[，。？：；‘’！“”—……、,]/gi)
    //     var z = []
    //     a.filter(function(item){
    //       if(item.slice(-1) != "市"){
    //         z.push(item) 
    //       }
    //     })
    //     if (z.length!==0){
    //       callback(new Error('请输入正确的地区格式'))
    //     }else{
    //       callback()
    //     }
    // };
    return {
      props: { multiple: true },
      id: [],
      productName: "",
      loanAppLabelIds: "",
      sortData: [],
      value: "",
      loanAppId: [],
      selectArr: "",
      cityoptions: provinceAndCityData,
      dialogFormVisible1: false,
      dialogVisible2: false,
      // 编辑
      form1: {
        id: "",
        loanAppId: "",
        matchRegion: "",
        name: "",
      },
      //新增
      form: {
        id: "",
        loanAppId: "",
        matchRegion: "",
        name: "",
      },
      rules:{
        matchRegion:[
          {  required: true, message: '请选择匹配地区', trigger: 'change'  }
        ],
         loanAppId:[
          {  required: true, message: '请选择产品名称', trigger: 'change'  }
        ]
      },
      // rules1:{
      //   matchRegion1:[
      //     { validator: validatePass1, trigger: 'blur' }
      //   ]
      // },
      inviolableRightsDto: {},
      fromConfig: [],
      tableData: [],
      total: 0,
      apptotal: 0,
      channelId: null,
      tableKey: 0,
      listQuery: {
        current: 1,
        size: 999,
        productId: "",
        state:2
      },
      channelConf: [],
      dialogFormVisible: false,
      listLoading: false,
    };
  },
  created() {
    this.findAll(this.listQuery);
    this.list()
  },

  methods: {
    async findAll(page) {
      if(page){this.listQuery.current = page}
      const res = await getRegionalProducts(this.listQuery);
      this.tableData = res.data.data;
      this.total = res.data.data.total;
      this.tableData.forEach(e => {
        e.enableSwitch = e.startStop === 1;
        e.enableSwitch1 = e.status === 1
      })
    },
    // 展示下拉框数据
    list(listQuery) {
      list(this.listQuery).then((res) => {
        if (res.data.code == 200) {
          this.selectArr = res.data.data.records;
        } else {
          this.$notify({
            title: "业务提示",
            message: res.data.msg,
            type: "fail",
            duration: 2000,
          });
        }
      });
      // console.log(this.total);
    },
    // 取消
    cancel(){
            this.dialogFormVisible = false;
            this.form.matchRegion = "";
            this.form.loanAppId = "";
    },
    cancel1(){
      this.dialogFormVisible1 = false;
      this.findAll();
    },
    // 添加
    add() {
      this.$refs['form'].validate((valid) => {
          if (valid) {
      var matchRegion = ''
      for (let index = 0; index < this.form.matchRegion.length; index++) {
        const element = this.form.matchRegion[index]
        var p = CodeToText[element[0]]
        var c = CodeToText[element[1]]
        var area = ''
        if (index === (this.form.matchRegion.length - 1)) {
          area = p + '-' + c
        } else {
          area = p + '-' + c + ','
        }
        matchRegion += area
      }
      this.form.matchRegion = matchRegion
        this.form.name = this.$refs.selectLable.selected.currentLabel 
        this.$confirm("新增提示！", "确认新增吗？", {
            confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(() => {
        this.regionalProductDto = this.form;
        addRegionalProducts(this.regionalProductDto).then((res) => {
          // console.log(res);
          if (res.data.code == 200) {
            this.dialogFormVisible = false;
            this.$notify({
              title: "业务提示",
              message: "新增成功",
              type: "success",
              duration: 2000,
            });
            (this.form.matchRegion = ""),
            (this.form.loanAppId = ""),
              this.findAll();
          } else {
            this.$notify({
              title: "业务提示",
              message: res.data.msg,
              type: "fail",
              duration: 2000,
            });
          }
        });
      })
      } else {
            return false;
          }
        });
    },
   
    //编辑
    async editLabel(row) {
      this.form1 = row
      // this.getLoanAppList()
      var matchRegion = []
      if (row.matchRegion.length === 0) {
        matchRegion = ''
      } else {
        matchRegion = row.matchRegion.split(',')
      }
      var area = []
      for (let index = 0; index < matchRegion.length; index++) {
        const element = matchRegion[index]
        if (element.indexOf('undefined') !== -1) {
          // console.log(1)
          this.form1.matchRegion = ''
        }
      }
      // console.log(this.loan)

      if (row.matchRegion === '' || row.matchRegion === null) {
        this.form1.matchRegion = ''
      } else if (matchRegion.length === 1) {
        // var index = region[0].indexOf('省') + 1
        var p = matchRegion[0].split('-')[0]
        var c = matchRegion[0].split('-')[1]
        // var p = region[0].substring(0, index)
        // var c = region[0].substring(index, region[0].length)
        var pCode = TextToCode[p].code
        var cCode = TextToCode[p][c].code
        var code = [pCode, cCode]
        area.push(code)
      } else {
        for (let i = 0; i < matchRegion.length; i++) {
          // var index1 = region[i].indexOf('省') + 1
          // var p1 = region[i].substring(0, index1)
          // var c1 = region[i].substring(index1, region[0].length)
          var p1 = matchRegion[i].split('-')[0]
          var c1 = matchRegion[i].split('-')[1]
          var pCode1 = TextToCode[p1].code
          var cCode1 = TextToCode[p1][c1].code
          var code1 = []
          code1.push(pCode1)
          code1.push(cCode1)
          area.push(code1)
        }
      }


      this.form1.matchRegion = area
      this.form1.id = row.id;
      this.form1.loanAppId = row.loanAppId;
      // this.form1.matchRegion = row.matchRegion;
      this.form1.name=row.name;
      this.dialogFormVisible1 = true;
    },
    submit() {
      var matchRegion = ''
      for (let index = 0; index < this.form1.matchRegion.length; index++) {
        const element = this.form1.matchRegion[index]
        var p = CodeToText[element[0]]
        var c = CodeToText[element[1]]
        var area = ''
        if (index === (this.form1.matchRegion.length - 1)) {
          area = p + '-' + c
        } else {
          area = p + '-' + c + ','
        }
        matchRegion += area
      }
      this.form1.matchRegion = matchRegion

      this.form1.name = this.$refs.selectLable1.selected.currentLabel 
      let regionalProductDto = this.form1;
    //   console.log(this.regionalProductDto);
      addRegionalProducts(JSON.parse(JSON.stringify(regionalProductDto))).then((res) => {
        // console.log(res);
        if (res.data.code == 200) {
          this.dialogFormVisible1 = false;
          this.$notify({
            title: "业务提示",
            message: "修改成功",
            type: "success",
            duration: 2000,
          });
          (this.form.productId = ""),
            (this.form.rightType = ""),
            (this.form.productName = ""),
            (this.form.limitedQuantity = ""),
            (this.form.sort = ""),
            this.findAll();
        } else {
          this.$notify({
            title: "业务提示",
            message: res.data.msg,
            type: "fail",
            duration: 2000,
          });
        }
      });
    },
    // 删除
     async handleDelete(row) {
      var that = this
      this.$confirm('删除提示！', '确认删除吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        removeByAppId({ id: row.id }).then((res) => {
          if (res.data.code === 200) {
            that.findAll()
          }else {
            this.$notify({
              title: "错误",
              message: res.data.msg,
              type: "fail",
              duration: 2000,
            });
          }
        })
      })
    },
    
  },
};
</script>

<style scoped>
.pic {
  width: 150px;
  margin-top: 10px;
  margin-left: 10px;
}
.ok {
  margin-left: 10px;
  margin-top: 10px;
  font-weight: 500;
  color: rgb(35, 248, 124);
}
.fail {
  margin-left: 10px;
  margin-top: 10px;
  font-weight: 500;
  color: rgb(240, 174, 76);
}
.info {
  margin-left: 10px;
  margin-top: 10px;
  font-weight: 500;
}
.info-name {
  margin-left: 50px;
  margin-top: 10px;
  color: rgb(172, 176, 177);
}
.title {
  margin-top: 10px;
  margin-left: 10px;
  font-size: 20px;
  font-weight: 400;
}
.box {
  margin-top: 10px;
  width: 100%;
  border: solid rgb(138, 219, 230) 2px;
}
.nick {
  font-size: 30px;
  font-weight: 600;
}
.link-top {
  margin-left: 10px;
  margin-top: 10px;
  width: 100%;
  height: 2px;
  border-top: solid rgb(138, 219, 230) 2px;
}
.link-title {
  margin-left: 10px;
  margin-top: 10px;
  width: 80px;
  height: 2px;
  border-top: solid rgb(172, 176, 177) 2px;
}
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
.right {
  display: flex;
  flex-direction: row-reverse;
}
</style>
